from Signals.Kill import Kill
from SistemaOperativo.Planificador import Planificador
from SistemaOperativo.Timer import Timer
import threading

class PlanificadorRR(Planificador):
    lock = threading.RLock()
    #Se crea con un quantum de tiempo
    def __init__(self, quantum):
        self.ready = []
        self.quantum = quantum
        self.timer = Timer(None, self.quantum)
        
    def addTask(self, pid, kernel):
        self.lock.acquire()
        try:
            self.ready.append(pid)
        finally:
            self.lock.release()
    
                
    def returnNextPid(self, kernel):
        if(len(self.ready) > 0):
            return self.ready.pop(0)
        else:
            print("No hay mas elementos en la cola de ready")
            kernel.interrupt(Kill())
            
    def reschedule(self, kernel):
        if len(self.ready)> 0:
            self.timer.set()
            print("readyTamanio", self.ready.__len__())
            super(PlanificadorRR, self).reschedule(kernel)
            if kernel.current_pid is not None:
                self.timer = Timer(kernel, self.quantum)
                self.timer.start()
        else:
            print("El planificador no tiene mas elementoslementos")
            
    def getQuantum(self):
        return self.quantum
    
    def terminarProceso(self):
        self.timer._stop()